$(function () {
    let searhWord = decodeURIComponent(getParam("keywords"));
    $(".input-xl").val(searhWord);
    search();
    $(".glyphicon-search").unbind("click").click(function () {
        var url = window.location.href;
        location.replace(changeURLArg(url, "keywords", $(".input-xl").val()));
        search();
    });
})

$(document).keyup(function (event) {
    if (event.keyCode == 13) {
        var url = window.location.href;
        location.replace(changeURLArg(url, "keywords", $(".input-xl").val()));
        //search();
    }
});

function getParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = location.search.substr(1).match(reg);
    if (r != null) return decodeURI(decodeURI(r[2]));
}

function search() {
    if ($(".input-xl").val() == "") {
        layer.msg("检索的内容不能为空！");
        return;
    }
    $("#details").empty();
    $.ajax({
        url: "/ret/knowledgeget/searchIndex",
        type: "post",
        dataType: "json",
        data: {
            keywords: $(".input-xl").val()
        },
        success: function (data) {
            let v = data.list.data;
            if (v.length > 0) {
                $("#ts").hide();
            } else {
                $("#ts").show();
            }
            for (var i = 0; i < v.length; i++) {
                let attach = JSON.parse(v[i].attachInfo);
                var fileName = v[i].fileName.substr(19)
                var extName = getType(fileName);
                $("#details").append('<div class="invoice-notes" style="margin-top:20px;border-bottom: 2px dashed #ccc;">' + '<h5>'
                    + (i + 1) + '、【' + getAttachTypeName(attach.modules) + '】' + fileName + '</h5>'
                    + '<div style="text-align: right;"><span style="margin-right: 20px">版本:' + attach.version + '</span><span style="margin-right: 10px">创建时间:' + attach.upTime + '</span></div>' +
                    '<a href="javascript:void(0);" onclick="openFileOnLine(\'' + extName + '\',\'' + v[i].attachId + '\',\'1\')" ><p>' + v[i].fileContent + '</p><a>' + '</div>');
            }
        }
    });
}

function getType(file) {
    var filename = file;
    var index1 = filename.lastIndexOf(".");
    var index2 = filename.length;
    var type = filename.substring(index1, index2);
    return type;
}

function changeURLArg(url, arg, arg_val) {
    var pattern = arg + '=([^&]*)';
    var replaceText = arg + '=' + arg_val;
    if (url.match(pattern)) {
        var tmp = '/(' + arg + '=)([^&]*)/gi';
        tmp = url.replace(eval(tmp), replaceText);
        return tmp;
    } else {
        if (url.match('[\?]')) {
            return url + '&' + replaceText;
        } else {
            return url + '?' + replaceText;
        }
    }
}
